import { delay, useBrowserPage, waitForSelector } from "@sker/core"
import { useCloseWs, useSend } from '@sker/runtime'
export default async (msg: any) => {
    const url = `https://s.weibo.com`;
    await useBrowserPage(async (page, browser) => {
        const ctx = browser.defaultBrowserContext();
        await ctx.overridePermissions(url, ['geolocation'])
        await page.setJavaScriptEnabled(true);
        await page.setViewport({
            width: 1920,
            height: 768
        });
        const cookies = await page.cookies(url)
        await page.deleteCookie(...cookies)
        await page.goto(url, {
            waitUntil: ['networkidle2']
        });
        const href = page.url();
        useSend(JSON.stringify({
            action: 'open',
            data: href
        }))
        try {
            const loginCardBtnJpU1 = await waitForSelector(page, '.LoginBtn_btn_10QRY', 5)
            useSend(JSON.stringify({
                action: 'get_login_btn',
                data: href
            }))
            if (loginCardBtnJpU1) {
                await loginCardBtnJpU1.click();
                useSend(JSON.stringify({
                    action: 'click_login_btn',
                    data: href
                }))
                await page.waitForNavigation()
                await delay(1000)
                const img = await waitForSelector(page, 'div.LoginPop_mabox_3Lyr6 > img', 100)
                if (!img) {
                    useSend(JSON.stringify({
                        action: 'get_login_fail',
                        data: href
                    }))
                } else {
                    let loginImage = await page.$eval('div.LoginPop_mabox_3Lyr6 > img', (img) => (img as HTMLImageElement).src);
                    if (loginImage.startsWith('https://weibo.com/newlogin')) {
                        useSend(JSON.stringify({
                            action: 'get_login_fail',
                            data: loginImage
                        }))
                        return;
                    }
                    useSend(JSON.stringify({
                        action: 'get_login_qrcode',
                        data: loginImage
                    }))
                    const tip = await waitForSelector(page, 'span.woo-tip-text > div.LoginPop_t1_2fuX8', 10)
                    if (tip) {
                        const txt = await page.$eval('span.woo-tip-text > div.LoginPop_t1_2fuX8', (div) => {
                            return (div as HTMLDivElement).innerText;
                        });
                        useSend(JSON.stringify({
                            action: 'get_scan_qrcode',
                            data: txt
                        }))
                        // 扫描成功
                        await page.waitForNavigation()
                        const url = page.url()
                        if (url.startsWith('https://weibo.com/u/')) {
                            // user
                        }
                        // 获取用户信息
                        const cookies = await page.cookies('https://weibo.com/')
                        useSend(JSON.stringify({
                            action: 'login_success',
                            data: url,
                            cookies
                        }))
                        const content = await page.content()
                        if (url.startsWith('https://s.weibo.com')) {
                            const re2 = /\$CONFIG\[\'(.*?)\'\]\s*=\s*\'(.*?)\'/g
                            const user: any = {}
                            for (let item of content.matchAll(re2)) {
                                const [, key, value] = item;
                                Reflect.set(user, key, value)
                            }
                            useSend(JSON.stringify({
                                action: 'get_userinfo',
                                data: {
                                    uid: user.uid,
                                    cookies,
                                    name: user.nick,
                                    avatar: user.avatar_large,
                                    gender: user.sex
                                }
                            }))
                        } else {
                            const re = /window\.\$CONFIG\s*=\s*(.*)\s*;\s*}\s*catch\(e\)/g
                            const result = re.exec(content)
                            if (result && result.length > 0) {
                                const res = result[1]
                                try {
                                    const CONFIG = JSON.parse(res.trim())
                                    const user = CONFIG?.user;
                                    if (user) {
                                        const uid = user.id;
                                        const name = user.screen_name;
                                        const avatar = user.avatar_large;
                                        useSend(JSON.stringify({
                                            action: 'get_userinfo',
                                            data: {
                                                uid,
                                                cookies,
                                                name,
                                                avatar,
                                            }
                                        }))
                                    }
                                } catch (e: any) { }
                            }
                        }
                    }
                }
            }
        } catch (e: any) {
            useSend(JSON.stringify({
                action: 'get_login_fail',
                data: e.message
            }))
        } finally {
            useCloseWs()
        }
    })
}
